package org.tigr.htc.common.sge;

/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

import java.util.Properties;

import org.tigr.htc.common.HTCConfig;

import com.sun.grid.jgdi.JGDI;
import com.sun.grid.jgdi.JGDIException;
import com.sun.grid.jgdi.JGDIFactory;

public class JGDILocator {
	private static JGDI singleton = null;
	private static final String DEFAULT_QMASTER_PORT = "6444";
	
	private JGDILocator() {
		// No-arguments constructor
	}
	
	public static JGDI getJGDI() throws JGDIException {
		if (singleton == null) {
			Properties sysProp = System.getProperties();
			
			String url;
			if (sysProp.containsKey("sgeRoot") && sysProp.containsKey("sgeCell")) {
				url = getUrlFromSystemProperties();
			} else {
				sysProp.list(System.out);
				url = getUrlFromConfigFile();
			}
			
			singleton = JGDIFactory.newInstance(url);
		}
		return singleton;
	}
	
	private static String getUrlFromSystemProperties() {
		String sgeRoot = System.getProperty("sgeRoot");
		String sgeCell = System.getProperty("sgeCell");
		String sgeQmasterPort = System.getProperty("sgeQmasterPort");
		if (sgeQmasterPort == null) {
			// If the port is not specified, use the default
			sgeQmasterPort = DEFAULT_QMASTER_PORT;
		}
		
		String url = getJgdiConnectionUrl(sgeRoot, sgeCell, sgeQmasterPort);
		return url;
	}
	
	private static String getUrlFromConfigFile() {
		String sgeRoot = HTCConfig.getProperty("sgeRoot");
		String sgeCell = HTCConfig.getProperty("sgeCell");
		// Attempt to get the config for the qmaster port, but specify the default if it's not there.
		String sgeQmasterPort = HTCConfig.getProperty("sgeQmasterPort", DEFAULT_QMASTER_PORT);
		
		String url = getJgdiConnectionUrl(sgeRoot, sgeCell, sgeQmasterPort);
		return url;
	}
	
	private static String getJgdiConnectionUrl(String sgeRoot, String sgeCell, String sgeQmasterPort) {
		String url = "bootstrap://" + sgeRoot + "@" + sgeCell + ":" + sgeQmasterPort;
		return url;
	}
	
	@Override
	public Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}

}
